package com.blockmeta.bbs.businesslibrary.widget;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import com.blankj.utilcode.util.LogUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.businesslibrary.util.ReportIssue;

/**
 * Created by AirThor
 * Date 2018/2/5.
 * 判断APP是否在运行
 */

public class ForegroundCallbacks implements Application.ActivityLifecycleCallbacks {
    private ForegroundCallbacks(){}
    private static volatile ForegroundCallbacks instance;
    private boolean isForground;
    private static final String  MAIN= "MainActivity";
    //打开的Activity数量统计
    private int activityStartCount = 0;
    /**
     * 应用切到后台
     */
    private boolean isAppForground = true;
    public static ForegroundCallbacks init(Application application){
        if (instance == null) {
            instance = new ForegroundCallbacks();
            application.registerActivityLifecycleCallbacks(instance);
        }
        return instance;
    }
    public static ForegroundCallbacks get(Application application){
        if (instance == null) {
            init(application);
        }
        return instance;
    }

    public boolean isForeground() {
        return isForground;
    }

    /**
     * 应用前后台切换，而非杀死
     * @return
     */
    public boolean isAppForground() {
        return isAppForground;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (activity.getLocalClassName().contains(MAIN)){
            isForground = true;
            LogUtils.d("author" + "forgroud");
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        activityStartCount++;
        //数值从0变到1说明是从后台切到前台
        if (activityStartCount == 1){
            isAppForground = true;
        }

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        activityStartCount--;
        //数值从1到0说明是从前台切到后台
        if (activityStartCount == 0){
            isAppForground = false;
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (activity.getLocalClassName().contains(MAIN)){
            ReportIssue.sendIssues(true);
            isForground = false;
            LogUtils.d("author" + "backgroud");
        }
    }
}
